/**
 * Historico de alteração
 *
 * Data         Autor   Descrição
 * 24/10/2010   Jerry   Criação do cabeçalho.
 *
 */

package railbee.banco.jdbc;

import java.sql.*;

public class ResourceManager
{
    private static String JDBC_DRIVER   = "org.postgresql.Driver";
    private static String JDBC_URL      = "jdbc:postgresql://localhost:5432/railbee";

    private static String JDBC_USER     = "postgres";
    private static String JDBC_PASSWORD = "1234";

    private static Driver driver = null;
    private static Connection connection;
    
    public static synchronized Connection getConnection() throws SQLException	
	{
		if(connection == null)
		{
			criarConexao();
		}
		return connection;
	}

    private static void criarConexao() throws SQLException
    {
        if (driver == null)
        {
            try
            {
                Class jdbcDriverClass = Class.forName( JDBC_DRIVER );
                driver = (Driver) jdbcDriverClass.newInstance();
                DriverManager.registerDriver( driver );
            }
            catch (Exception e)
            {
                System.out.println( "Failed to initialise JDBC driver" );
                e.printStackTrace();
            }
        }

        connection = DriverManager.getConnection(
       			JDBC_URL,
       			JDBC_USER,
       			JDBC_PASSWORD
       	);
    }


	public static void close(Connection conn)
	{
		try {
			if (conn != null) conn.close();
		}
		catch (SQLException sqle)
		{
			sqle.printStackTrace();
		}
	}

	public static void close(PreparedStatement stmt)
	{
		try {
			if (stmt != null) stmt.close();
		}
		catch (SQLException sqle)
		{
			sqle.printStackTrace();
		}
	}

	public static void close(ResultSet rs)
	{
		try {
			if (rs != null) rs.close();
		}
		catch (SQLException sqle)
		{
			sqle.printStackTrace();
		}

	}
	
	public Connection abrirConexao() throws SQLException
	{
		return getConnection();
	}
	
	protected void fecharConexao() throws SQLException
	{
		getConnection().close();
	}

}
